package util;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by Lenovo
 * DATA:2023/10/19
 * Http相关的工具类。
 **/
public class HttpUtils {
    /**
     * 获取下载文件的大小
     * @param url
     * @return
     * @throws IOException
     */
    public static long getHttpFileContentLength(String url) throws IOException {
        int contentLength;
        HttpURLConnection httpURLConnection=null;
        try{
          httpURLConnection = getHttpURLConnection(url);
            contentLength=httpURLConnection.getContentLength();
        }finally {
           if(httpURLConnection!=null){
               httpURLConnection.disconnect();
           }
        }
        return contentLength;
    }
    /**
     * 分块下载
     */
    public static HttpURLConnection getHttpURLConnection(String url,long startPos,long endPos) throws IOException {
        HttpURLConnection httpURLConnection = getHttpURLConnection(url);
        LogUtils.info("下载的区间是：{}-{}",startPos,endPos);
        if(endPos!=0){
            httpURLConnection.setRequestProperty("Range","bytes="+startPos+"-"+endPos);
        }else{
            httpURLConnection.setRequestProperty("Range","bytes="+startPos+"-");
        }
        return httpURLConnection;
    }
    /**
     *  https://dldir1.qq.com/qqfile/qq/PCQQ9.7.17/QQ9.7.17.29230.exe
     * 获取HttpURLConnection链接对象(建立链接通道)
     * @param url
     * @return
     */
    public static HttpURLConnection getHttpURLConnection(String url) throws IOException {
        URL httpUrl = new URL(url);
        HttpURLConnection httpURLConnection = (HttpURLConnection) httpUrl.openConnection();
        /**
         *向文件所在的服务器发送标识信息。
         * 当我们使用浏览器去访问某个网站的时候，会将当前浏览器的版本，
         * 操作系统版本等信息的表示发送到网站所在的服务器中，当用代码去访问网站的时候
         * 也需要将这个表示发送过去，
         * */
        httpURLConnection.setRequestProperty(
                "User-Agent",
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/244.178.44.111 Safari/537.36"
        );
        return httpURLConnection;
    }
    /**
     * 获取下载文件的名字。
     */
    public static String getHtpFileName(String url) {
        int index = url.lastIndexOf("/");
        System.out.println("下载文件的名字："+url.substring(index+1));
        return url.substring(index+1);
    }
}
